<template>
  <div id="await-animation">
    <Row type='flex' justify="end" class="selectItem">
      <Button @click.native="openDefault('1')">默认设置</Button>
      <Poptip trigger="hover" content="支持格式：.jpg、.png；规格：180*120；大小：≤100KB" placement="bottom-end" word-wrap width="200">
        <Button type="primary" style="margin-left:24px" @click.native="openDefault('2')">上传物料</Button>
      </Poptip>
      <Modal title="确认提示"
             width='400'
             v-model="delReason">
        <Form :model="delValidate"
              ref="delValidate"
              :label-width="50"
              :rules="delRule">
          <FormItem label="原因:"
                    prop="remark">
            <Input v-model="delValidate.remark"
                   style="width:300px;" :maxlength='100'
                   type="textarea"
                   :autosize="{minRows: 5,maxRows: 10}"
                   placeholder="请输入删除原因" />
                   <p style="text-align: right;width:300px">{{delValidate.remark.length}}/100</p>
          </FormItem>
        </Form>
        <div slot="footer"
             class="foot">
          <Button class="btn" style="margin-right:16px;width:72px"
                  @click='cancelDel'>取消</Button>
          <Button type="primary"
                  class="btn"
                  style="width:72px"
                  @click="sureDel">确认</Button>
        </div>
      </Modal>
    </Row>
    <div class="animation-list">
      <Row type='flex' class="container">
        <Col v-for="(item,idx) in tableList" :key='idx' class="animation-item">
          <div class="img-container">
            <img :src="item.url" alt="">
            <!-- <Icon type="ios-close-circle-outline" size="25" class="icon-cancel" @click="cancelChoose(item)" /> -->
            <Icon type="md-close-circle" size="25" class="icon-cancel" @click="cancelChoose(item)"  />
            <!-- <Poptip confirm title="你确定要删除吗？" class="icon-cancel" placement='top' @on-ok="cancelChoose" width="150">
              <Icon type="ios-close-circle-outline" size="24" />
            </Poptip> -->
          </div>
          <p>{{item.createTime}}</p>
        </Col>
      </Row>
      <div v-show="contentShow"
           style="text-align: center;margin-top:114px;">
        <img :width="320"
             :height="240"
             :src="error">
      </div>
    </div>
    <Row type='flex' justify="end" style="padding:20px">
      <Col>
        <Page :total="pageObj.total"
            :current="pageObj.pageIndex"
            :page-size="pageObj.pageSize"
            show-sizer
            show-total
            @on-change='changePageIndex'
            @on-page-size-change='changePageSize' />
      </Col>
    </Row>
    <Drawer v-model="modalDefault"
            :title="title"
            :mask-closable="true"
            :closable="true"
            :transfer='false'
            class="shopDrawer"
            width="540">
      <Form ref="formValidate"
            :model="formValidate"
            :rules="ruleValidate"
            :label-width="100"
            class="shopDrawer_form">
        <FormItem label="上传图片:"
                  prop="url"
                  class="set_ct_form_up">
          <Upload ref="upload" class="load-img" :before-upload="handleUpload"
                  :format="['jpg','png']"
                  :max-size="100"
                  :on-format-error="handleFormatError"
                  :on-exceeded-size="handleMaxSize"
                  :data='uploadParmas'
                  :on-success="handleSuccess"
                  :on-error='handleErr'
                  type="drag"
                  :show-upload-list="false"
                  :action="$config.uploadImg">
            <img :src="formValidate.url?formValidate.url:defaultUrl1" id='imgage'
            :class="title === '默认设置' && formValidate.url ?'defaultStyle': 'materialStyle'"
                 alt="">
            <p v-if="formValidate.url" class="replace_tit" @click.stop="delMaterialUrl">删除</p>
          </Upload>
          <div class="standard">
            <p>支持格式：jpg、png</p>
            <p>规格：180*120</p>
            <p>大小：≤100K</p>
            <p>名称：不能为中文</p>
          </div>
        </FormItem>
      </Form>
      <div class="demo-drawer-footer footer1">
          <Button @click="handleReset"
                  style="width:72px">取消</Button>
          <Button type="primary" :disabled='isDisabled'
                  @click="handleSubmit"
                  style="width:72px;margin-left:20px">确认</Button>
        </div>
    </Drawer>
  </div>
</template>

<script>
import { hex_md5 } from '@/libs/md5'
import error from '@/assets/images/error-page/error.svg'
import { lookAnimationList, addSingleAnimation, delSingleAnimation } from '@/api/setting'
export default {
  name: 'global_setting_page_5',
  data () {
    return {
      isDisabled: false,
      contentShow: false,
      error: error,
      tableList: [],
      title: '默认设置',
      pageObj: {
        total: 0,
        pageIndex: 1,
        pageSize: 10
      },
      contentBase: '',
      delReason: false, // 删除原因状态
      delValidate: {
        remark: ''
      },
      delRule: {
        remark: { required: true, message: '删除原因不能为空', trigger: 'change' }
      },
      deviceFimwareId: '',
      modalDefault: false,
      uploadParmas: {
        project: 'material',
        type: 'animation'
      },
      formValidate: {
        url: '',
        imageName: '',
        md5: ''
      },
      ruleValidate: {
        url: {
          required: true, message: '上传的物料不能为空'
        }
      },
      defaultUrl1: require('@/assets/images/add.png'),
      defaultUrl: require('@/assets/images/player.jpg')
    }
  },
  methods: {
    changePageIndex (index) {
      this.pageObj.pageIndex = index
      this.getData()
    },
    changePageSize (size) {
      this.pageObj.pageSize = size
      this.pageObj.pageIndex = 1
      this.getData()
    },
    cancelChoose (row) {
      this.delReason = true
      this.deviceFimwareId = row.deviceStandbyId
    },
    cancelDel () {
      this.$refs.delValidate.resetFields()
      this.delReason = false
    },
    sureDel () {
      this.$refs.delValidate.validate((valid) => {
        if (valid) {
          delSingleAnimation({
            deviceStandbyId: this.deviceFimwareId,
            remark: this.delValidate.remark
          }).then(res => {
            if (res.data.status === 200) {
              this.$Message.success('删除成功！')
              this.delReason = false
              this.getData()
            } else {
              this.$Message.error(`${res.data.error}`)
            }
          })
        }
      })
    },
    handleUpload (file) {
      var reader = new FileReader()
      if (file) {
        // 将文件以Data URL形式读入页面
        var imgUrlBase64 = reader.readAsDataURL(file)
        console.log(imgUrlBase64)
        var that = this
        reader.onload = function (e) {
          that.formValidate.md5 = hex_md5(reader.result)
        }
      }
    },
    getSize (url, name) {
      var img = new Image()
      img.src = url
      var _this = this
      img.onload = function () {
        if (img.width === 180 && img.height === 120) {
          // 此处处理图片名称
          _this.formValidate.url = url
          _this.formValidate.imageName = name
        } else {
          _this.formValidate.url = ''
          _this.$Notice.warning({
            title: '上传的图片规格不符',
            duration: 1.5
          })
        }
      }
    },
    handleSuccess (response, file) {
      this.$refs.formValidate.resetFields()
      let reg = /[\u4e00-\u9fa5]/
      if (response.full_img_url) {
        if (!reg.test(file.name)) {
          this.getSize(response.full_img_url, file.name)
        } else {
          this.$Notice.warning({
            title: '上传图片名称不能为中文'
          })
        }
      }
    },
    handleErr () {
      this.$Message.error('上传失败！')
    },
    handleFormatError (file) {
      this.$Notice.warning({
        title: '上传的图片格式错误'
      })
    },
    handleMaxSize (file) {
      this.$Notice.warning({
        title: '上传的图片大小不能超过100k'
      })
    },
    handleReset () {
      this.modalDefault = false
      this.$refs.formValidate.resetFields()
    },
    handleSubmit () {
      this.$refs.formValidate.validate(valid => {
        if (valid) {
          this.isDisabled = true
          let type = this.title === '默认设置' ? 0 : 1
          setTimeout(() => {
            addSingleAnimation({
              ...this.formValidate, type: type
            }).then(res => {
              this.isDisabled = false
              if (res.data.status === 200) {
                this.modalDefault = false
                this.$Message.success('上传成功！')
                this.getData()
              } else {
                this.$Message.error({
                  content: `${res.data.error}`,
                  duration: 1
                })
              }
            })
          }, 600)
        }
      })
    },
    openDefault (type) {
      this.modalDefault = true
      if (type === '1') {
        this.title = '默认设置'
        lookAnimationList({
          type: 0,
          shopId: '',
          offset: 0,
          limit: 10
        }).then(res => {
          if (res.data.status === 200) {
            if (res.data.data.length > 0) {
              this.formValidate.url = res.data.data[0].url
            }
          } else {
            this.$Message.error(`${res.data.error}`)
          }
        })
      } else if (type === '2') {
        this.title = '上传物料'
      }
    },
    delMaterialUrl () {
      this.formValidate.url = ''
    },
    // 获取待机动画列表
    getData () {
      this.contentShow = false
      lookAnimationList({
        type: 1,
        shopId: '',
        offset: this.pageObj.pageSize * (this.pageObj.pageIndex - 1),
        limit: this.pageObj.pageSize
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.tableList = result.data || []
          this.pageObj.total = result.totalCount || 0
          if (result.data.length < 1) {
            this.contentShow = true
          }
          if (result.data.length / this.pageObj.pageSize === 0) {
            if (this.pageObj.pageIndex > 1) {
              this.pageObj.pageIndex--
              this.getData()
            }
          }
        } else {
          this.$Message.error(`${result.error}`)
        }
      })
    }
  },
  mounted () {
    this.getData()
  },
  watch: {
    delReason (val) {
      if (!val) {
        this.$refs.delValidate.resetFields()
      }
    },
    modalDefault (val) {
      if (!val) {
        this.$refs.formValidate.resetFields()
      }
    }
  }
}
</script>

<style lang='less'>
  #await-animation {
    .selectItem {
      padding: 20px;
      .ivu-poptip-inner {
        background: #585E6B;
      }
      .ivu-poptip-body-content-inner {
        color: #fff;
      }
      .ivu-poptip-popper[x-placement^="bottom"] .ivu-poptip-arrow:after {
        border-bottom-color: #585E6B;
      }
    }
    .animation-list {
      padding: 0 60px;
      .container {
        width: 1050px;
        min-width: 1050;
        margin: auto;
        .animation-item:nth-of-type(5n) {
          margin-right: 0;
        }
        .animation-item {
          margin: 35px 36px 35px 0;
          .img-container {
            width: 180px;
            height: 120px;
            position: relative;
            .icon-cancel {
              position: absolute;
              right: 2px;
              top: 2px;
            }
            img {
              width: 100%;
              height: 100%;
              display: block;
            }
          }
          p {
            background: #F8F8F9;
            text-align: center;
            height: 40px;
            line-height: 40px;
          }
        }
      }
    }
    .shopDrawer {
      .shopDrawer_form {
        margin-top: 48px;
        .defaultStyle {
          width: 180px;
          height: 120px;
        }
        .materialStyle {
          width:96px;
          height:96px;
        }
        .load-img {
          display: inline-block;
          position:relative;
          img {
            display: inline-block;
            vertical-align: top;
          }
          .replace_tit{
            width: 100%;
            position: absolute;
            left: 0;
            bottom: 0;
            opacity: 0.6;
            filter:alpha(opacity=60);
            background: #ED4014;
            color: #fff;
          }
        }
        .standard {
          width:165px;
          height:72px;
          line-height:18px;
          color: #464C5B;
          margin-left:24px;
          display: inline-block;
          vertical-align:top;
        }
      }
      .footer1{
        width: 100%;
        position: absolute;
        bottom: 0;
        left: 0;
        border-top: 1px solid #e8e8e8;
        padding: 10px 16px;
        text-align: right;
        background: #fff;
      }
    }
  }
</style>
